import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import ci from 'miniprogram-ci';
import ora from 'ora';

const __filenameNew = fileURLToPath(import.meta.url);

export default async (modeItem, version, user) => {
  const { name, value } = modeItem;
  const distUrl = path.resolve(__filenameNew, '../../dist/build/mp-weixin');
  const projectConfigUrl = path.resolve(distUrl, './project.config.json');

  const projectConfig = fs.readFileSync(projectConfigUrl, { encoding: 'utf8' });

  const { appid, setting } = JSON.parse(projectConfig);

  let allNum = 0;
  let doneNum = 0;
  const spinner = ora({
    text: `正在上传${doneNum}/${allNum}`,
    color: 'green',
  });
  spinner.start();
  const project = new ci.Project({
    appid: appid,
    type: 'miniProgram',
    projectPath: distUrl,
    privateKeyPath: path.resolve(__filenameNew, `../private.${appid}.key`),
  });
  const uploadResult = await ci.upload({
    project,
    version,
    desc: `上传用户${user}，${name}。`,
    setting: {
      es6: true,
      es7: true,
      minify: true,
      minifyJS: true,
      minifyWXML: true,
      minifyWXSS: true,
      autoPrefixWXSS: true,
    },
    onProgressUpdate: (task) => {
      if (task._status === 'doing') allNum += 1;
      else if (task._status === 'done') doneNum += 1;
      spinner.text = `正在上传${doneNum}/${allNum}`;
    },
    robot: value,
  });
  spinner.succeed(uploadResult);
};
